<?php

class ReporteMailController extends Controller {

    /**
     * @var string the default layout for the views.
     */
    public $layout = '//layouts/column2';

    public function filters() {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    public function actionIndex() {
        $model = new Mail();
        $model->scenario = 'reporte';
        $model->date_first = date('d/m/Y');
        $model->date_last = date('d/m/Y');
        $generar = null;

        $clientes = Contacto::model()->findAll();

        if ($_POST) {
            $model->fechas = $_POST['Mail']['fechas'];
            $generar = 'GENERAR';

            if ($model->fechas) {

                $fechas = explode(' - ', $model->fechas);

                $model->date_first = $fechas[0];
                $model->date_last = $fechas[1];
            } else {

                Yii::app()->user->setFlash('error', 'Por favor seleccione un rango de fechas para el reporte');
            }
        }

        $reporte = $this->generarReporteEnviados($model);


        $this->render('index', array(
            'model' => $model,
            'clientes' => $clientes,
            'reporte' => $reporte,
            'generar' => $generar,
        ));
    }

    private function generarReporteEnviados($model) {

        $report = array();
        $report['categories'] = array();
        $report['series'] = array();




        $inicio = DateTime::createFromFormat('d/m/Y', $model->date_first)->setTime(0, 0, 0);
        $fin = DateTime::createFromFormat('d/m/Y', $model->date_last)->setTime(0, 0, 0);
        $report['subtitle'] = ' Desde: ' . $inicio->format('d-m-Y') . '  Hasta: ' . $fin->format('d-m-Y');
        $interval = DateInterval::createFromDateString('1 day');
        $period = new DatePeriod($inicio, $interval, $fin);
        $dias = 0;
        foreach ($period as $date) {
            $dias++;
        }



        switch (true) {
            case ($dias == 0): {

                    $report['tipo'] = ' por horas';
                    $interval = DateInterval::createFromDateString('1 hour');
                    $fin->add(new DateInterval('PT23H59M59S'));
                    $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular

                    foreach ($period as $value) {

                        $command = Yii::app()->db->createCommand();
                        $command->select('COUNT(mail.id) as cnt');
                        $command->from('mail');
                        $report['categories'][] = $value->format('H:i:s');
                        $fechaIni = $value->format('Y-m-d H:i:s');
                        $fechaFin = $value->format('Y-m-d H:') . '59:59';
                        $command->where("mail.fecha_envio between '" . $fechaIni . " 'and '" . $fechaFin . "'");
                        $command->andWhere('mail.estado = "' . Mail::ESTADO_ENVIADO . '"');
                        if ($model->contacto_id)
                            $command->andWhere('contacto_id = :contacto_id', array(':contacto_id' => $model->contacto_id));

                        $result = $command->queryAll();
                        $results[$fechaIni] = $result;
                    }
                    break;
                }
            case ($dias >= 1 && $dias <= 30): {

                    $report['tipo'] = ' por días';
                    $interval = DateInterval::createFromDateString('1 day');
                    $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
                    foreach ($period as $value) {
                        $command = Yii::app()->db->createCommand();
                        $command->select('COUNT(mail.id) as cnt');
                        $command->from('mail');
                        $report['categories'][] = $value->format('d/m/Y');
                        $fechaIni = $value->format('Y-m-d H:i:s');
                        $fechaFin = $value->format('Y-m-d ') . '23:59:59';
                        $command->where("mail.fecha_envio between '" . $fechaIni . " 'and '" . $fechaFin . "'");
                        $command->andWhere('mail.estado = "' . Mail::ESTADO_ENVIADO . '"');
                        if ($model->contacto_id)
                            $command->andWhere('contacto_id = :contacto_id', array(':contacto_id' => $model->contacto_id));

                        $result = $command->queryAll();
                        $results[$fechaIni] = $result;
                    }
                    break;
                }
            case ($dias >= 31 && $dias <= 83): {
                    $report['tipo'] = ' por semanas';
                    if ($inicio->format('D') != 'Mon') {
                        $inicio->modify('last monday');
                    }
                    if ($fin->format('D') == 'Mon') {
                        $fin->add(new DateInterval('P6DT23H59M59S'));
                    }
                    $interval = DateInterval::createFromDateString('1 week');
                    $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
                    foreach ($period as $value) {
                        $inicio = $value->format('Y-m-d H:i:s');
                        $report['categories'][] = $value->format('d/m/Y');
                        $value->add(new DateInterval('P6DT23H59M59S'));
                        $fin = $value->format('Y-m-d H:i:s');
                        $command = Yii::app()->db->createCommand();
                        $command->select('COUNT(mail.id) as cnt');
                        $command->from('mail');
                        $command->where("mail.fecha_envio between '" . $inicio . " 'and '" . $fin . "'");
                        $command->andWhere('mail.estado = "' . Mail::ESTADO_ENVIADO . '"');
                        if ($model->contacto_id)
                            $command->andWhere('contacto_id = :contacto_id', array(':contacto_id' => $model->contacto_id));

                        $result = $command->queryAll();
                        $results[$inicio] = $result;
                    }
                    break;
                }

            case ($dias >= 84): {

                    $report['tipo'] = ' por meses';
                    $interval = DateInterval::createFromDateString('1 month');
                    $period = new DatePeriod($inicio, $interval, $fin);

                    foreach ($period as $value) {
                        $inicio = $value->modify('first day of this month')->format('Y-m-d H:i:s');
                        $report['categories'][] = $value->modify('first day of this month')->format('d/m/Y');

                        $fin = $value->modify('last day of this month')->add(new DateInterval('PT23H59M59S'));
                        $fin = $date->format('Y-m-d H:i:s');
                        //                 error

                        $command = Yii::app()->db->createCommand();
                        $command->select('COUNT(mail.id) as cnt');
                        $command->from('mail');

                        $command->where("mail.fecha_envio between '" . $inicio . " 'and '" . $fin . "'");
                        $command->andWhere('mail.estado = "' . Mail::ESTADO_ENVIADO . '"');
                        if ($model->contacto_id)
                            $command->andWhere('contacto_id = :contacto_id', array(':contacto_id' => $model->contacto_id));

                        $result = $command->queryAll();
                        $results[$inicio] = $result;
                    }
                    break;
                }
            default: {

                    return null;
                }
        }



        $serie = array();
        $serie['type'] = 'column';
        $serie['name'] = 'Enviados';
        $serie['data'] = array();
        if (isset($results)) {
            foreach ($results as $result) { // categoria
                $count = 0;
                foreach ($result as $r) { //serie
                    $count = (int) $r['cnt'];
                }
                $serie['data'][] = $count;
            }
        }

        $report['series'][] = $serie;

//        $report['subtitle'] = 'Desde: ' . (gettype($inicio) == "string") ? $inicio : $inicio->format('Y-m-d H:i:s') . ' hasta: ' . (gettype($fin) == "string") ? $fin : $fin->format('Y-m-d H:i:s');

        return $report;
    }

    /**
     * retorna el numero de dias entre las fechas
     * @param type $fecha_i
     * @param type $fecha_f
     * @return type $dias
     * @author Mauricio Chamorro
     */
    public function dias_transcurridos($fecha_i, $fecha_f) { //
        $dias = (strtotime($fecha_i) - strtotime($fecha_f)) / 86400;
        $dias = abs($dias);
        $dias = floor($dias);
        return $dias;
    }

    /**
     * retorna la menor, mayor y total de incidencias en sms por motivo
     * @param type $model
     * @return type $dias
     * @author Mauricio Chamorro
     */
}
